import { observable, action } from '@formily/reactive'
import { todoType } from '@/apis'

interface todoContent {
  todos: todoType[]
}

const obs = observable<todoContent>({
  todos: [
    { id: 1111, content: "学习vue2", done: false },
    { id: 1112, content: "睡觉", done: false }
  ]
})

const allCount = observable.computed(() => obs.todos.length)
const doneCount = observable.computed(() => obs.todos.reduce((pre, todo) => pre + (todo.done ? 1 : 0), 0))

// 添加todo
const addTodo = action.bound!((data: todoType) => {
  const flag = obs.todos.findIndex(item => item.content === data.content)
  if(flag === -1) {
    obs.todos.push(data)
  } else {
    alert('已存在相同事件')
  }
})

// 删除todo
const removeTodo = action.bound!((id: number) => {
  obs.todos = obs.todos.filter(todoObj => todoObj.id !== id)
})

// 切换todo完成状态
const toggleTodo = action.bound!((id: number, done: boolean) => {
  obs.todos = obs.todos.map(todoObj => {
    if (todoObj.id === id) return { ...todoObj, done }
    else return todoObj
  })
})

// 切换全选状态
const toggleCheckAll = action.bound!((done: boolean) => {
  obs.todos = obs.todos.map(todoObj => {
    return { ...todoObj, done }
  })
})

// 删除已完成
const deleteDone = action.bound!(() => {
  obs.todos = obs.todos.filter(todoObj => {
    return !todoObj.done
  })
})

export {
  obs, addTodo, removeTodo, toggleTodo, toggleCheckAll, deleteDone, allCount, doneCount
}

